from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from admi.models import Useradmin, UserAdminIntroduce
from django.contrib.auth.hashers import make_password
from django.contrib.auth.hashers import check_password
from userbook.models import Userinfo, Userintroduce
from book.models import Booktitle, BookSection
from useradmin.models import Usermanagement
from django.core.paginator import Paginator
import json


#我封装的权限验证，安全验证
from .authority.admin_authority import validate_user







@csrf_exempt
@require_POST
# 添加管理带加密
def add_user(request):
    try:
        # 解析请求体中的 JSON 数据
        data = json.loads(request.body.decode('utf-8'))

        # 提取数据
        name = data.get('name')
        introduce = data.get('introduce')
        raw_password = data.get('password')

        if not name or not raw_password:
            return JsonResponse({'error': 'Name and password are required'}, status=400)

        # 检查用户名是否已存在
        if Useradmin.objects.filter(name=name).exists():
            return JsonResponse({'error': '用户名不能重复'}, status=400)

        # 创建用户实例
        user = Useradmin(
            name=name
        )
        user.save()

        # 加密密码
        encrypted_password = make_password(raw_password)

        # 创建用户介绍实例
        user_intro = UserAdminIntroduce(
            user=user,  # 关联用户
            introduce=introduce,
            password=encrypted_password
        )
        user_intro.save()

        return JsonResponse({'message': '用户创建完成'}, status=201)

    except json.JSONDecodeError:
        return JsonResponse({'error': 'Invalid JSON'}, status=400)
    except ValueError as e:
        return JsonResponse({'error': str(e)}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)




@csrf_exempt
@require_POST
# 验证登录，解密
def login(request):
    try:
        # 解析请求体中的 JSON 数据
        data = json.loads(request.body.decode('utf-8'))

        # 提取数据
        uuid_str = data.get('uuid')
        name = data.get('name')
        password = data.get('password')


        # 调用验证函数
        validation_response = validate_user(name, password, uuid_str, 1)
        if validation_response:
            return validation_response

        # 获取对应的用户信息
        try:
            user = Useradmin.objects.get(name=name)
            user_intro = UserAdminIntroduce.objects.get(user=user)
        except Useradmin.DoesNotExist:
            return JsonResponse({'error': '不对'}, status=404)
        except UserAdminIntroduce.DoesNotExist:
            return JsonResponse({'error': '不对'}, status=404)

        return JsonResponse({'message': '验证通过'}, status=200)

    except json.JSONDecodeError:
        return JsonResponse({'error': '无效 JSON'}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)






@csrf_exempt
@require_POST
# 权限获取数据验证
def get_user_info(request):
    try:
        # 解析前端传递的JSON数据
        data = json.loads(request.body.decode('utf-8'))
        uuid_str = data.get('uuid')
        name = data.get('name')
        password = data.get('password')
        # 获取分页参数
        page = int(data.get('page', 2))  # 当前页，默认为第2页
        per_page = int(data.get('per_page', 5))  # 每页条数，默认为5条

        # 调用验证函数
        validation_response = validate_user(name, password, uuid_str, 2)
        if validation_response:
            return validation_response

        # 获取所有Userinfo数据
        user_info = Userinfo.objects.all()

        # 分页
        paginator = Paginator(user_info, per_page)
        page_info = paginator.get_page(page)

        # 构建返回数据
        response_data = {
            'users_info': list(page_info.object_list.values()),
            'page': page,
            'per_page': per_page,
            'total_pages': paginator.num_pages,
            'total_records': paginator.count
        }

        return JsonResponse(response_data, status=200)

    except json.JSONDecodeError:
        return JsonResponse({'error': 'Invalid JSON'}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)







@csrf_exempt
@require_POST
# 获取用户详细
def get_user_details(request):
    try:
        # 解析请求体中的 JSON 数据
        data = json.loads(request.body.decode('utf-8'))
        uuid = data.get('uuids')

        uuid_str = data.get('uuid')
        name = data.get('name')
        password = data.get('password')
        # 调用验证函数
        validation_response = validate_user(name, password, uuid_str, 5)
        if validation_response:
            return validation_response



        if not uuid:
            return JsonResponse({'error': '请求错误'}, status=400)

        # 根据 UUID 获取 Userinfo 实例
        try:
            user_info = Userinfo.objects.get(uuid=uuid)
        except Userinfo.DoesNotExist:
            return JsonResponse({'error': '请求失败'}, status=404)

        # 获取对应的 Userintroduce 和 Usermanagement 实例
        try:
            user_introduce = Userintroduce.objects.get(user=user_info)
        except Userintroduce.DoesNotExist:
            user_introduce = None  # 用户介绍不存在

        try:
            user_management = Usermanagement.objects.get(user=user_info)
        except Usermanagement.DoesNotExist:
            user_management = None  # 用户管理信息不存在

        # 构建返回数据
        response_data = {
            'user_info': {
                'uuid': user_info.uuid,
                'name': user_info.name,
                'age': user_info.age,
                'email': user_info.email,
                'pub_time': user_info.pub_time,
                'is_active': user_info.is_active,
                'favorite_books': user_info.favorite_books,
                'history_books': user_info.history_books,
            },
            'user_introduce': {
                'introduce': user_introduce.introduce if user_introduce else None,
                'grade': user_introduce.grade if user_introduce else None,
                'portrait': user_introduce.portrait.url if user_introduce and user_introduce.portrait else None,
                'score': user_introduce.score if user_introduce else None
            },
            'user_management': {
                'control': user_management.control if user_management else None,
                'password': user_management.password if user_management else None
            }
        }

        return JsonResponse(response_data, status=200)

    except json.JSONDecodeError:
        return JsonResponse({'error': 'Invalid JSON'}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)






@csrf_exempt
@require_POST
# 获取图书
def get_user_book(request):
    try:
        # 解析前端传递的JSON数据
        data = json.loads(request.body.decode('utf-8'))
        uuid_str = data.get('uuid')
        name = data.get('name')
        password = data.get('password')
        # 获取分页参数
        page = int(data.get('page', 2))  # 当前页，默认为第2页
        per_page = int(data.get('per_page', 5))  # 每页条数，默认为5条

        # 调用验证函数
        validation_response = validate_user(name, password, uuid_str, 2)
        if validation_response:
            return validation_response

        # 获取所有Booktitle数据
        user_info = Booktitle.objects.all()

        # 分页
        paginator = Paginator(user_info, per_page)
        page_info = paginator.get_page(page)

        # 构建返回数据
        response_data = {
            'users_info': list(page_info.object_list.values()),
            'page': page,
            'per_page': per_page,
            'total_pages': paginator.num_pages,
            'total_records': paginator.count
        }

        return JsonResponse(response_data, status=200)

    except json.JSONDecodeError:
        return JsonResponse({'error': 'Invalid JSON'}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)











@csrf_exempt
@require_POST
# 获取指定图书的详细信息+章节+用户
def get_users_books(request):
    try:
        # 解析请求体中的 JSON 数据
        data = json.loads(request.body.decode('utf-8'))
        book_uuid = data.get('uuids')
        uuid_str = data.get('uuid')
        name = data.get('name')
        password = data.get('password')

        # 调用验证函数
        validation_response = validate_user(name, password, uuid_str, 5)
        if validation_response:
            return validation_response

        if not book_uuid:
            return JsonResponse({'error': '请求错误'}, status=400)

        # 根据 book_uuid 查询 Booktitle
        try:
            book_info = Booktitle.objects.get(bookUuid=book_uuid)
        except Booktitle.DoesNotExist:
            return JsonResponse({'error': '未找到指定的图书'}, status=404)

        # 获取对应的 BookSection 实例列表
        book_sections = BookSection.objects.filter(book=book_info)

        # 获取对应的 Userinfo 实例
        user_info = book_info.author

        # 获取 Userintroduce 信息
        try:
            user_introduce = Userintroduce.objects.get(user=user_info)
        except Userintroduce.DoesNotExist:
            user_introduce = None

        # 构建返回数据
        response_data = {
            'user_info': {
                'name': user_info.name,
                'age': user_info.age,
                'email': user_info.email,
                'uuid': str(user_info.uuid),
            },
            'user_introduce': {
                'introduce': user_introduce.introduce if user_introduce else None,
                'grade': user_introduce.grade if user_introduce else None,
                'portrait': user_introduce.portrait.url if user_introduce and user_introduce.portrait else None,
                'score': user_introduce.score if user_introduce else None,
            },
            'book_info': {
                'bookUuid': str(book_info.bookUuid),
                'name': book_info.name,
                'book_time': book_info.book_time,
                'publish_time': book_info.publish_time,
                'frequency': book_info.frequency,
            },
            'book_sections': [
                {
                    'titleUuid': str(section.titleUuid),
                    'nametitle': section.nametitle,
                    # 返回的内容
                    # 'content': section.content,
                    'introduce_time': section.introduce_time,
                }
                for section in book_sections
            ]
        }

        return JsonResponse(response_data, status=200)

    except json.JSONDecodeError:
        return JsonResponse({'error': 'Invalid JSON'}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


